public class CheckInventoryController
{
    public List<SelectOption> ShipmentCityList{get;set;}
    public List<CheckEntry> CheckEntryList{get;set;}
    public String SelectedCityValue{get;set;}
    public  CheckInventory__c CheckObj{get;set;}
    public string RSMId {get;set; }
    public List<SelectOption> TypeList{get;set;}
    public String TypeSelectedValue{get;set;}
    public map<string,CheckInventory__c> UpdateCheckList{get;set;}   
    public List<ShipmentCity__c> ShipmentInventoryList{get;set;}//城市库存信息
    public CityInventory__c cityNew{get;set;}//用于绑于到页面中
    
    public CheckInventoryController()
    {
        LoadData();
    }
    
    public void LoadData()
    {
        cityNew=new CityInventory__c();
        List<id> IdList=new List<id>();
        CommonRecursionMethod commonMethod=new CommonRecursionMethod();
        commonMethod.getRSMId(String.valueOf(UserInfo.getUserId()),IdList);
        if(IdList.size()>0)
            RSMId=IdList[0];
        else
            RSMId=NULL;
             
        CheckObj=new CheckInventory__c();
        
        if(ShipmentCityList==NULL)
            ShipmentCityList=new List<SelectOption>();
         else
             ShipmentCityList.clear();
         
        if(CheckEntryList==NULL)
            CheckEntryList=new List<CheckEntry>();
        else
            CheckEntryList.clear();
            
        if(UpdateCheckList==NULL)    
             UpdateCheckList=new map<string,CheckInventory__c>();
        else
            UpdateCheckList.clear();
            
       if(ShipmentInventoryList==NULL)
             ShipmentInventoryList=new List<ShipmentCity__c>();
       else
           ShipmentInventoryList.clear();
             
       LoadCityList();
       
        if(TypeList==NULL)
            TypeList=new List<SelectOption>();
        else
            TypeList.clear();
            
         TypeList.add(new SelectOption('Trade','Trade'));
         TypeList.add(new SelectOption('Medical','Medical'));
         
         //删除草稿状态的数据
       /*  set<id> deleteCheckList=new set<id>();
        for(CheckInventoryItem__c items:[select id,CheckInventory__c from CheckInventoryItem__c 
                                                            where CheckInventory__r.CityInventory__r.OwnerId=:UserInfo.getUserId() 
                                                            and Approval_Stage__c='草稿'])
        {
            deleteCheckList.add(items.CheckInventory__c);
        }    
        delete [select id from CheckInventory__c where id in: deleteCheckList];*/
    }
    
    //获取城市列表
    public PageReference GetCityList()
    {
        LoadCityList();
        CheckEntryList.clear();
        return null;
    }
    public void LoadCityList()
    {
        ShipmentCityList.clear();
         boolean isTrade=true;
        if(TypeSelectedValue==NULL)
              isTrade=true;
        else
        {
            if(TypeSelectedValue=='Trade')
                 isTrade=true;
             else
                 isTrade=false;
         }  
         for(ShipmentCity__c sCity:[select id,ShipmentCity__r.Name,SalesCity__c  from ShipmentCity__c where IsTrade__c=:isTrade and OwnerId=:UserInfo.getUserId()])
        {
            ShipmentCityList.add(new SelectOption(sCity.id, sCity.ShipmentCity__r.Name ));
            ShipmentInventoryList.add(sCity);
        }
    }
    public PageReference QueryAction()
    {
        QueryCheckList();
        return null;
    }
    
    public void QueryCheckList()
    {
        CheckEntryList.clear();
        List<CityInventory__c> CityInventoryList=[select id,Product__r.Name,Product__c,CheckIn__c,DeliveryRequest__c,TotalCheckInventroy__c 
                                                                           from CityInventory__c  
                                                                           where ShipmentCity__c=:SelectedCityValue and TheoryInventoryNumber__c>0];
                                                                           
        for(CityInventory__c cInventory:CityInventoryList)
        {
            CheckEntry entry=new CheckEntry();
            entry.IdString=cInventory.Id;
            entry.ProductName=cInventory.Product__r.Name;
            entry.ProductId=cInventory.Product__c;
            entry.TheoryInventory=cInventory.CheckIn__c-cInventory.DeliveryRequest__c-cInventory.TotalCheckInventroy__c;
            //entry.ActualInventory=0;
            entry.CheckInNumber=cInventory.CheckIn__c;
            entry.CheckOutNumber=cInventory.DeliveryRequest__c;
            entry.ReasonNumber1=0;
            entry.ReasonNumber2=0;
            entry.ReasonNumber3=0;
            entry.ReasonNumber4=0;
            CheckEntryList.add(entry);
        }
    }
   
    public PageReference Submit()
    {
        try
        {
            if(CheckObj.CheckDate__c==NULL)
                throw new CustomException('请选择一个日期');
            if(CheckObj.CheckDate__c>system.today())
                throw new CustomException('日期不能大于今天');
         }
         catch(Exception ex)
         {
             ApexPages.addMessages(ex);
              return null;
         }
            
        if(UpdateCheckList!=NULL && UpdateCheckList.size()>0)
        {
            //查找
            List<Id> checkItemIdList=new List<Id>();
            List<CheckInventoryItem__c> updateCheckItemList=new List<CheckInventoryItem__c>();
            List<CheckInventory__c> updateCheckInventoryList=new List<CheckInventory__c>();
            List<CheckInventoryItem__c> deleteCheckItemList=new List<CheckInventoryItem__c>();
       
            for(CheckEntry entry:CheckEntryList)
            {
                if(entry.CheckId!=NULL)
                    checkItemIdList.add(entry.CheckId);
            }
           
            if(checkItemIdList.size()>0)
            {
                updateCheckInventoryList=[select CheckDate__c,Year__c,Month__c from CheckInventory__c where id in:checkItemIdList]; 
               for(CheckInventory__c cInventory:updateCheckInventoryList)
               {
                    cInventory.CheckDate__c=CheckObj.CheckDate__c;
                    cInventory.Year__c=CheckObj.CheckDate__c.Year();
                    cInventory.Month__c=CheckObj.CheckDate__c.Month();   
               }
               update updateCheckInventoryList;
               
               //找出check Item
               map<string,List<CheckInventoryItem__c>>  mapCheckItemList=new map<string,List<CheckInventoryItem__c>>();
               for(CheckInventoryItem__c checkItem:[select id,Type__c,Unit__c,Approval_Stage__c,CheckInventory__c from CheckInventoryItem__c where CheckInventory__c in:checkItemIdList])
               {
                   if(mapCheckItemList.containsKey(checkItem.CheckInventory__c))
                   {
                       List<CheckInventoryItem__c> items=mapCheckItemList.get(checkItem.CheckInventory__c);
                       items.add(checkItem);
                       mapCheckItemList.put(checkItem.CheckInventory__c,items);
                   }
                   else
                   {
                       List<CheckInventoryItem__c> items=new List<CheckInventoryItem__c>();
                        items.add(checkItem);
                       mapCheckItemList.put(checkItem.CheckInventory__c,items);
                   }
               }
               
               for(CheckEntry entry:CheckEntryList)
               {
                   if(mapCheckItemList.containsKey(entry.CheckId))
                   {
                        List<CheckInventoryItem__c> items=mapCheckItemList.get(entry.CheckId);
                        for(CheckInventoryItem__c cItem:items)
                        {
                             cItem.Approval_Stage__c='已提交';
                             
                            if(cItem.Type__c=='过期或近期产品')
                            {
                                 if(entry.ReasonNumber1!=0)
                                 {
                                      cItem.Unit__c=entry.ReasonNumber1;
                                     updateCheckItemList.add(cItem);
                                 }
                                 else
                                 {
                                     deleteCheckItemList.add(cItem);
                                 }
                            }
                            if(cItem.Type__c=='出货破损')
                            {
                                if(entry.ReasonNumber2!=0)
                                {
                                    cItem.Unit__c=entry.ReasonNumber2;
                                    updateCheckItemList.add(cItem);
                                 }
                                 else
                                 {
                                     deleteCheckItemList.add(cItem);
                                 }
                            }
                            if(cItem.Type__c=='仓库丢失')
                            {
                                 if(entry.ReasonNumber3!=0)
                                 {
                                    cItem.Unit__c=entry.ReasonNumber3;
                                    updateCheckItemList.add(cItem);
                                 }
                                 else
                                 {
                                     deleteCheckItemList.add(cItem);
                                 }
                            }
                            if(cItem.Type__c=='其他原因')
                            {
                                if(entry.ReasonNumber4!=0)
                                {
                                    cItem.Unit__c=entry.ReasonNumber4;
                                    updateCheckItemList.add(cItem);
                                 }
                                 else
                                 {
                                     deleteCheckItemList.add(cItem);
                                 }
                            }    
                           
                        }
                   }
               }
               update updateCheckItemList;
               delete deleteCheckItemList;
           }
            //发起审批流
            for(CheckInventory__c cInventory:updateCheckInventoryList)
            {
                try
                {
                     Approval.ProcessSubmitRequest req1 = new Approval.ProcessSubmitRequest();   
                     req1.setObjectId(cInventory.Id);
                     Approval.ProcessResult result = Approval.process(req1);
                     cInventory.ApprovalID__c=(String)result.getNewWorkitemIds().get(0);
                     cInventory.ApprovalRSM__c=RSMId;
                 }
                 catch(Exception ex){}
            }
          
            update updateCheckInventoryList;
        }
        else
        {
            SaveData(true);
        }
       
        PageReference  pr=new PageReference('/'+SelectedCityValue);
        pr.setRedirect(true);
        return pr;
    }
    public PageReference Save()
    {
         try
        {
            if(CheckObj.CheckDate__c==NULL)
                throw new CustomException('请选择一个日期');
             if(CheckObj.CheckDate__c>system.today())
                throw new CustomException('日期不能大于今天');
         }
         catch(Exception ex)
         {
             ApexPages.addMessages(ex);
              return null;
         }
        SaveData(false);
        return null;
    }
    public void SaveData(boolean isSubmit)
    {
       // map<string,CheckInventory__c> checkList=new map<string,CheckInventory__c>();
        List<CheckInventoryItem__c> checkItemList=new List<CheckInventoryItem__c>();
        List<CheckInventory__c> ApprovalCheckList=new List<CheckInventory__c>();
        for(CheckEntry entry:CheckEntryList)
        {
                CheckInventory__c check=new CheckInventory__c();
                check.CityInventory__c=entry.IdString;
                check.CheckDate__c=CheckObj.CheckDate__c;
                check.Year__c=CheckObj.CheckDate__c.Year();
                check.Month__c=CheckObj.CheckDate__c.Month();
                check.ShipmentUnit__c=entry.CheckInNumber;
                check.DeliveryUnit__c=entry.CheckOutNumber;     
                check.ApprovalID__c='';   
                check.ApprovalRSM__c=RSMId;
                UpdateCheckList.put(entry.IdString+entry.ProductId,check);
        }
        insert UpdateCheckList.values();
        
        List<CheckInventory__c> UpdateCheckApprovalList=new List<CheckInventory__c>();
        for(CheckEntry entry:CheckEntryList)
        {
            CheckInventory__c check=UpdateCheckList.get(entry.IdString+entry.ProductId);
            if(check!=NULL)
            {
               ApprovalCheckList.add(check);
                entry.CheckId=check.Id;
                string StageString='';
                if(isSubmit)
                    StageString='已提交';
                 else
                     StageString='草稿';
                if(entry.ReasonNumber1!=0)
                    checkItemList.add(CreateCheckItem(check.Id,'过期或近期产品',entry.ReasonNumber1,'',StageString));
                if(entry.ReasonNumber2!=0)
                    checkItemList.add(CreateCheckItem(check.Id,'出货破损',entry.ReasonNumber2,'',StageString));
                if(entry.ReasonNumber3!=0)
                    checkItemList.add(CreateCheckItem(check.Id,'仓库丢失',entry.ReasonNumber3,'',StageString));
                if(entry.ReasonNumber4!=0)
                    checkItemList.add(CreateCheckItem(check.Id,'其他原因',entry.ReasonNumber4,entry.ReasonDescription4,StageString));
            }
        }
        insert checkItemList;
        
        if(isSubmit)
        {
            for(CheckInventory__c check:ApprovalCheckList)
            {
                try
                {
                     Approval.ProcessSubmitRequest req1 = new Approval.ProcessSubmitRequest();   
                     req1.setObjectId(check.Id);
                     Approval.ProcessResult result = Approval.process(req1);
                     check.ApprovalID__c=(String)result.getNewWorkitemIds().get(0);
                     check.ApprovalRSM__c=RSMId;
                 }catch(Exception ex)
                 {}
            }                 
           update ApprovalCheckList;
        }
    }
    public CheckInventoryItem__c CreateCheckItem(string checkId,string typeString,Integer reasonNum,string reasonDes,string stage)
    {
        CheckInventoryItem__c CheckItem=new CheckInventoryItem__c();
        CheckItem.CheckInventory__c=checkId;
        CheckItem.Type__c=typeString;
        CheckItem.Unit__c=reasonNum;
        CheckItem.Approval_Stage__c=stage;
        checkItem.ReasonDescription__c=reasonDes;
        return CheckItem;
    }
    //添加产品
    public PageReference AddProduct()
    {
        try
        {
            boolean flag=false;
            if(SelectedCityValue!=NULL && cityNew.Product__c!=NULL)
            {
                List<CityInventory__c> cityList=[select id from CityInventory__c where ShipmentCity__c=:SelectedCityValue and Product__c=:cityNew.Product__c];
                if(cityList.size()>0)
                {
                    for(CheckEntry entry:CheckEntryList )
                    {
                        if(entry.ProductId==cityNew.Product__c)
                            flag=true;
                    }
                    if(!flag)
                    {
                        CityInventory__c cityInventory=[select id,Product__r.Name,Product__c,CheckIn__c,DeliveryRequest__c,TotalCheckInventroy__c 
                                                                                   from CityInventory__c  
                                                                                   where ShipmentCity__c=:SelectedCityValue and Product__c=:cityNew.Product__c];
                        CheckEntry entry=new CheckEntry();
                        entry.IdString=cityInventory.Id;
                        entry.ProductName=cityInventory.Product__r.Name;
                        entry.ProductId=cityInventory.Product__c;
                        entry.CheckInNumber=cityInventory.CheckIn__c;
                        entry.CheckOutNumber=cityInventory.DeliveryRequest__c;
                        entry.ReasonNumber1=0;
                        entry.ReasonNumber2=0;
                        entry.ReasonNumber3=0;
                        entry.ReasonNumber4=0;
                        CheckEntryList.add(entry);
                    }
                }
                else
                {
                    throw new CustomException('该产品不在当前的Warehouse');
                }
            }
            else
            {
                throw new CustomException('请选择城市和产品');
            }
       }
       catch(Exception ex)
       {
           ApexPages.addMessages(ex);
           return null;
       }
        return null;
    }
}